//
//  COIPA.swift
//  KOLHub
//
//  Created by Ruthless on 2023/7/31.
//

import UIKit
import StoreKit
import HDeviceIdentifier

class COIPA: NSObject {
    static let shared = COIPA()
    static var hasAddObsersver = false
    var vc: UIViewController?
    private var purchID: String = ""
    override init() {
        super.init()
        if !COIPA.hasAddObsersver {
            SKPaymentQueue.default().add(self)
            COIPA.hasAddObsersver = true
        }
    }
    
    func start(_ productId: String) {
        if SKPaymentQueue.canMakePayments() {
            getProduct(from: productId)
        } else {
            self.vc?.view.makeToast("Unavailable for purchase", position: .center)
        }
    }
    
    private func getProduct(from id: String) {
        self.purchID = id
        let request = SKProductsRequest(productIdentifiers: [id])
        request.delegate = self
        request.start()
        
    }
}

extension COIPA: SKPaymentTransactionObserver, SKProductsRequestDelegate {
    func paymentQueue(_ queue: SKPaymentQueue, updatedDownloads downloads: [SKDownload]) {
        
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
        
    }
    
    func paymentQueueDidChangeStorefront(_ queue: SKPaymentQueue) {
        print("111111111111111111111111111111111111111111111111")
    }
    
    func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
        print("222222222222222222222222222222222222222222")
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, didRevokeEntitlementsForProductIdentifiers productIdentifiers: [String]) {
        print("33333333333333333333333333333333")
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
        print("Error")
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, shouldAddStorePayment payment: SKPayment, for product: SKProduct) -> Bool {
        return true
    }
    
    func requestDidFinish(_ request: SKRequest) {
//        DispatchQueue.main.async {
//            self.vc?.view.hideToastActivity()
//        }
        
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch transaction.transactionState {
            case .purchased:
                self.completeTran(tran: transaction)
                SKPaymentQueue.default().finishTransaction(transaction)
            case .purchasing:
                self.vc?.view.makeToastActivity(.center)
            case .failed:
                self.vc?.view.hideToastActivity()
                self.vc?.view.makeToast("Payment failure", position: .center)
                SKPaymentQueue.default().finishTransaction(transaction)
            case .restored:
                self.vc?.view.hideToastActivity()
                self.vc?.view.makeToast("The product has been purchased", position: .center)
                SKPaymentQueue.default().finishTransaction(transaction)
            default:
                self.vc?.view.hideToastActivity()
//                self.vc?.view.makeToast("Please try again later!", position: .center)
//                SKPaymentQueue.default().finishTransaction(transaction)
                break
            }
        }
    }
    
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        let product = response.products
//        if product.count == 0 {
//            DispatchQueue.main.async {
////                self.vc?.view.makeToast("Unable to get purchase information", position: .center)
//            }
//            return
//        }
        
        for pro in product {
            if pro.productIdentifier == self.purchID {
                let payment = SKPayment(product: pro)
                SKPaymentQueue.default().add(payment)
                break
            }
        }

    }
}

extension COIPA {
    private func completeTran(tran: SKPaymentTransaction) {
        let recvURL = Bundle.main.appStoreReceiptURL
        let receiptData = try? Data(contentsOf: recvURL!)
        let encodeStr = receiptData?.base64EncodedString(options: .endLineWithLineFeed)
        self.vc?.view.makeToastActivity(.center)

        CONetwork.sendRequest(provider: moneyProvider, target: .pay(orderId: tran.transactionIdentifier ?? "", receiptData: encodeStr ?? "")) { _ in
            self.vc?.view.hideToastActivity()
            self.vc?
                .view.makeToast("Payment success", position: .center)
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "PaySuccess"), object: nil)
        } failedBlock: { _, error in
            self.vc?.view.hideToastActivity()
            self.vc?.view.makeToast("Payment failure", position: .center)
        }
    }
    
    private func failedTransaction(tran: SKPaymentTransaction) {
        SKPaymentQueue.default().finishTransaction(tran)
    }
    
    private func restoreTransaction(tran: SKPaymentTransaction) {
        SKPaymentQueue.default().finishTransaction(tran)
    }
}
